package org.freespace.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.freespace.mapper.EnvironmentMachineMapper;
import org.freespace.mapper.JobMapper;
import org.freespace.mapper.TestplanMapper;
import org.freespace.model.Environment;
import org.freespace.mapper.EnvironmentMapper;
import org.freespace.model.EnvironmentMachine;
import org.freespace.model.Job;
import org.freespace.model.Testplan;
import org.freespace.service.IEnvironmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuqi
 * @since 2023-05-29
 */
@Service
public class EnvironmentServiceImpl extends ServiceImpl<EnvironmentMapper, Environment> implements IEnvironmentService {

    @Autowired
    JobMapper jobMapper;

    @Autowired
    TestplanMapper testplanMapper;

    @Autowired
    EnvironmentMachineMapper environmentMachineMapper;
    @Override
    public List<EnvironmentMachine> getJobEnvInfo(Integer jobId) {
        Job job = jobMapper.selectById(jobId);
        String envId = job.getEnvId();
        String ips = job.getIps();
        LambdaQueryWrapper<EnvironmentMachine> wrapper = Wrappers.<EnvironmentMachine>lambdaQuery()
                .in(EnvironmentMachine::getEnvId, envId.split(",", -1))
                .in(EnvironmentMachine::getIp, ips.split(",", -1))
                .orderByDesc(EnvironmentMachine::getEnvId);

        return  environmentMachineMapper.selectList(wrapper);
    }

    @Override
    public List<EnvironmentMachine> getEnvMachine(String envId) {
        Wrapper<EnvironmentMachine> wrapper = Wrappers.<EnvironmentMachine>lambdaQuery().in(EnvironmentMachine::getEnvId, envId.split(",", -1));
        List<EnvironmentMachine> environmentMachines = environmentMachineMapper.selectList(wrapper);
        return environmentMachines;
    }

    @Override
    public Set<String> getEnvMachineIps(String envId) {
        List<EnvironmentMachine> envMachine = getEnvMachine(envId);
        Set<String> ips = envMachine.parallelStream().map(m -> m.getIp()).collect(Collectors.toSet());
        return ips;
    }
}
